from django.db import models
from django.contrib.auth import get_user_model
import markdown
import os
from django.utils import timezone
from django.contrib.auth.models import User


class UserFeedback(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    rating = models.FloatField(choices=[(i * 0.5, f"{i * 0.5}") for i in range(11)])  # 0 to 5 in increments of 0.5
    feedback_type = models.CharField(max_length=100)  # Feedback type as a string
    content = models.TextField()  # Detailed feedback content
    timestamp = models.DateTimeField(default=timezone.now)  # Submission timestamp

    def __str__(self):
        return f"Feedback from {self.user} at {self.timestamp}"

    @classmethod
    def export_feedback_to_md(cls, filepath="feedback_report.md"):
        feedbacks = cls.objects.select_related('user').order_by('feedback_type', '-timestamp')
        report_lines = []

        current_type = None
        for feedback in feedbacks:
            # Start a new category if feedback_type changes
            if feedback.feedback_type != current_type:
                current_type = feedback.feedback_type
                report_lines.append(f"\n## {current_type}\n")

            # Format each feedback entry
            report_lines.append(f"### {feedback.user.username} - {feedback.timestamp.strftime('%Y-%m-%d %H:%M:%S')}")
            report_lines.append(f"- **Rating**: {feedback.rating}")
            report_lines.append(f"- **Type**: {feedback.feedback_type}")
            report_lines.append(f"- **Content**:\n\n{feedback.content}\n")

        # Convert the report to markdown format
        markdown_content = "\n".join(report_lines)
        with open(filepath, "w", encoding="utf-8") as md_file:
            md_file.write(markdown_content)
